package com.lagou.edu.filter;

import com.lagou.edu.bean.RequestCount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @date 2020/5/27 10:34
 */
@Slf4j
@Component
public class IpFilter implements GlobalFilter, Ordered {

    @Value("${ip.registerCount}")
    Integer ipRegisterCount;

    @Value("${ip.rejectTime}")
    Integer rejectTime;

    private static Map<String, CopyOnWriteArrayList<RequestCount>> ipRegisterCountMap = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookiesMap = request.getCookies();
        HttpCookie httpCookie = cookiesMap.getFirst("lagouSessionId");
        String path = request.getURI().getPath();
//        if (httpCookie == null || (httpCookie != null && httpCookie.equals("0"))){
        if (httpCookie == null || (httpCookie != null && httpCookie.equals("0"))){
            if (path.contains("/user/info")){
                response.setStatusCode(HttpStatus.FORBIDDEN);
                String msg = "用户信息获取失败";
                DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        //IP防暴刷
        if (path.contains( "/user/register")){
            String ip = request.getRemoteAddress().getHostName();
            log.info("当前访问ip: {}", ip);
            CopyOnWriteArrayList<RequestCount> requestIpRegisterCountList = ipRegisterCountMap.get(ip);
            if (!CollectionUtils.isEmpty(requestIpRegisterCountList)){
                if (requestIpRegisterCountList.size() > ipRegisterCount){
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    String msg = "您的操作太频繁，请稍后再试！";
                    DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }else{
                    RequestCount requestCount = new RequestCount(path, System.currentTimeMillis());
                    requestIpRegisterCountList.add(requestCount);
                    ipRegisterCountMap.put(ip, requestIpRegisterCountList);
                }
            }
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Scheduled(cron="0/10 * *  * * ? ")
    public void cleanExpiredIp(){
        log.info("清理过期ip缓存。。。");
        Set<Map.Entry<String, CopyOnWriteArrayList<RequestCount>>> ipRegisterEntry = ipRegisterCountMap.entrySet();
        ipRegisterEntry.forEach(elemSet -> {
            CopyOnWriteArrayList<RequestCount> requestCounts = elemSet.getValue();
            requestCounts.forEach(requestCount -> {
                if (System.currentTimeMillis() - requestCount.getExpire() > rejectTime * 1000){
                    requestCounts.remove(requestCount);
                }
            });

            String ip = elemSet.getKey();
            if (CollectionUtils.isEmpty(requestCounts)){
                ipRegisterCountMap.remove(ip);
            }
        });

    }
}
